<?php

namespace app\admin\controller\newhouse\building;

use app\common\controller\Backend;
use think\Db;
use think\Log;

/**
 * 楼盘信息
 *
 * @icon fa fa-circle-o
 */
class Items extends Backend
{
    /**
     * Items模型对象
     * @var \app\admin\model\newhouse\building\Items
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\newhouse\building\Items;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 代理商 开发商权限设置
            $where1='1=1';

            $group = $this->auth->getGroups()[0];
            $group_name=$group['name'];
            if($group_name=='楼盘开发商'){
                $where1 .= " AND developer_adminid=".$this->auth->id;
            }else if($group_name=='代理商案场负责人'){
                //$where1 .= " AND agent_adminid=".$this->auth->id;
                // 不限制大家看
            }

            $total = $this->model
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

         
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if(isset($params['area'])){
                    $array=explode('/',$params['area']);

                    if(sizeof($array)>0) $params['area_province']=$array[0];
                    if(sizeof($array)>1) $params['area_city']=$array[1];
                    if(sizeof($array)>2) $params['area_district']=$array[2];
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['create_userid'] = $this->auth->id;

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();

        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        /// 权限设置
        $group = $this->auth->getGroups()[0];
        $group_name=$group['name'];
        $where1='1=1';
        if($row->create_userid != $this->auth->id){
            // 如果不是自己录入的，就要进行下面的权限判断
        
            if($group_name=='开发商案场负责人' || $group_name=='楼盘开发商'){
                // 不是自己负责的不给编辑
                if($row->developer_adminid!=$this->auth->id){
                    $this->error(__('You have no permission'));
                }
            }
            else if($group_name=='代理商案场负责人' || $group_name=='楼盘代理公司'){
                // 不是自己负责的不给编辑
                if($row->agent_adminid != $this->auth->id){
                    $this->error(__('You have no permission'));
                }
            }else if($group_name=='Admin group'){
                
                
            }else{
                $this->error(__('You have no permission'));
            }
        }
        $buildingPictureType = \app\admin\model\newhouse\building\Picturetype::all();
        $this->view->assign('buildingPictureType',$buildingPictureType);

        /// 读取当前值
        $commissionPolicyModel=new \app\admin\model\newhouse\building\Policy;
        $policies = $commissionPolicyModel->where('building_id=' . $ids)->select();

        /// 加载图片
        $picture_values=[];
        $pictures = \app\admin\model\newhouse\building\Pictures::all(['building_id'=>$ids]);
        
        foreach($buildingPictureType as $key=>$value){
            $picture_values['v_' . $value->id] = ''; // 初始化
        }
        foreach($pictures as $key=>$value){
            if(!empty($picture_values['v_' . $value->typeid])) $picture_values['v_' . $value->typeid] .= ',';
            $picture_values['v_' . $value->typeid] .= $value->path;
        }
        $this->view->assign('pictures', $picture_values);

        /// 所有房产类型
        $buildingTypes = \app\admin\model\newhouse\building\Types::all();
        for($i=0;$i<sizeof($buildingTypes);$i++){
            $buildingTypes[$i]['has'] = "";
            $buildingTypes[$i]['price'] = "";
            $buildingTypes[$i]['commission_policy'] = "";
            foreach($policies as $key1=>$value1){
                if($buildingTypes[$i]->id == $value1->type_id){
                    $buildingTypes[$i]['has'] = "true";
                    $buildingTypes[$i]['price'] = $value1->price;
                    $buildingTypes[$i]['commission_policy'] = $value1->commission_policy;
                    break;
                }
            }
            
        }
        $this->view->assign('buildingTypes',$buildingTypes);
        

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if(isset($params['area'])){
                    $array=explode('/',$params['area']);

                    if(sizeof($array)>0) $params['area_province']=$array[0];
                    if(sizeof($array)>1) $params['area_city']=$array[1];
                    if(sizeof($array)>2) $params['area_district']=$array[2];
                }
                /// 佣金政策
                $commision_ids = $this->request->post("buildingTypesId/a");
                if(!empty($commision_ids)){
                    foreach($commision_ids as $key=>$value){
                        $policy_model=new \app\admin\model\newhouse\building\Policy;
                        // 如果有过了就不要再多写一次数据库了
                        $tmpList = $policy_model->where("building_id=$ids AND type_id=$value")->select();
                        if(!empty($tmpList)){
                            $policy_model = $tmpList[0];
                        }
                        $policy_model->building_id = $ids;
                        $policy_model->type_id     = $value;
                        $policy_model->price =$this->request->post('buildingTypesPrice_'.$value);
                        $policy_model->commission_policy=$this->request->post('buildingTypesPolicy_'.$value);
                        $policy_model->createtime=time();
                        $policy_model->create_userid = $this->auth->id;
                        $policy_model->save();
                    }
                }
                // 如果有佣金政策被删除了
                $policy_model=new \app\admin\model\newhouse\building\Policy;
                $tmpList = $policy_model->where("building_id=$ids")->select();
        
                foreach($tmpList as $key=>$value){
                    $remove=false;
                    if(!empty($commision_ids)){
                        if(in_array($value->type_id,$commision_ids)){
                            $remove=false;
                        }
                        else{
                            //删除不存在的选项
                            $remove=true;
                        }
                    }else{
                        $remove=true;
                    }
                    if($remove){
                        $value->delete();
                    }
                }
                
                $result = false;


                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['update_userid'] = $this->auth->id;
                    $result = $row->allowField(true)->save($params);
                    // 同步pictures
                    $picture_controller=new \app\admin\controller\newhouse\building\Pictures();
                    $pictures_params = $this->request->post("picture/a");

                    $picture_controller->sync($ids,$pictures_params);
                    Db::commit();

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    public function changePicture(){
        $id=$this->request->request('id');
        $picture_path=$this->request->request('picture_path');
        
        
        $row=$this->model->get($id);
        $row->picture=$picture_path;
        $row->save();
        $this->success();
    }
    public function view($ids = null){
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        //
        
        $buildingPictureType = \app\admin\model\newhouse\building\Picturetype::all();
        $this->view->assign('buildingPictureType',$buildingPictureType);

        /// 读取当前值
        $commissionPolicyModel=new \app\admin\model\newhouse\building\Policy;
        $policies = $commissionPolicyModel->where('building_id=' . $ids)->select();

        /// 加载图片
        $picture_values=[];
        $pictures = \app\admin\model\newhouse\building\Pictures::all(['building_id'=>$ids]);
        
        foreach($buildingPictureType as $key=>$value){
            $picture_values['v_' . $value->id] = []; // 初始化
        }
        foreach($pictures as $key=>$value){
            $picture_values['v_' . $value->typeid][]= [$value->path,$value->mem,$value->id];
        }
        $this->view->assign('pictures', $picture_values);

        /// 所有房产类型
        $buildingTypes = \app\admin\model\newhouse\building\Types::all();
        for($i=0;$i<sizeof($buildingTypes);$i++){
            $buildingTypes[$i]['has'] = "";
            $buildingTypes[$i]['price'] = "";
            $buildingTypes[$i]['commission_policy'] = "";
            foreach($policies as $key1=>$value1){
                if($buildingTypes[$i]->id == $value1->type_id){
                    $buildingTypes[$i]['has'] = "true";
                    $buildingTypes[$i]['price'] = $value1->price;
                    $buildingTypes[$i]['commission_policy'] = $value1->commission_policy;
                    break;
                }
            }
            
        }
        $this->view->assign('buildingTypes',$buildingTypes);
        
        // 楼盘标签
        $label_ids = $row->labels;
        $labels = Labels::getStrFromIds($label_ids);

        $this->view->assign('labels',$labels);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
     /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    /// 权限设置
                    $group = $this->auth->getGroups()[0];
                    $group_name=$group['name'];
                    $where1='1=1';
                    if($group_name=='开发商案场负责人' || $goup_name='楼盘开发商'){
                        // 不是自己负责的不给编辑
                        if($v->developer_adminid!=$this->auth->id){
                            $this->error(__('You have no permission'));
                        }
                    }
                    else if($group_name=='代理商案场负责人' || $group_name=='楼盘代理公司'){
                        // 不是自己负责的不给编辑
                        if($v->agent_adminid != $this->auth->id){
                            $this->error(__('You have no permission'));
                        }
                    }else if($group_name=='Admin group'){

                    }else{
                        $this->error(__('You have no permission'));
                    }
                    
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                  /// 权限设置
                    $group = $this->auth->getGroups()[0];
                    $group_name=$group['name'];
                    $where1='1=1';
                    if($group_name=='开发商案场负责人' || $goup_name='楼盘开发商'){
                        // 不是自己负责的不给编辑
                        if($v->developer_adminid!=$this->auth->id){
                            $this->error(__('You have no permission'));
                        }
                    }
                    else if($group_name=='代理商案场负责人' || $group_name=='楼盘代理公司'){
                        // 不是自己负责的不给编辑
                        if($v->agent_adminid != $this->auth->id){
                            $this->error(__('You have no permission'));
                        }
                    }else if($group_name=='Admin group'){

                    }else{
                        $this->error(__('You have no permission'));
                    }
                $count += $v->delete(true);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
